package teacher;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet("/StudentSearchServlet")
public class StudentSearchServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String keyword = request.getParameter("keyword");
        // 获取班级ID参数
        int classId = Integer.parseInt(request.getParameter("classId"));
        HttpSession session = request.getSession();
        Integer teacherId = (Integer) session.getAttribute("teacher_id");

        if (teacherId == null) {
            response.sendRedirect("teacher_student.jsp");
            return;
        }

        try {
            Connectmysql conn = new Connectmysql(
                    "jdbc:mysql://localhost:3306/exam",
                    "root",
                    "root",
                    "com.mysql.cj.jdbc.Driver"
            );

            if (conn.open()) {
                // 修复1：添加班级ID过滤条件
                // 修复2：添加DISTINCT避免重复
                // 修复3：添加status字段
                String sql = "SELECT DISTINCT s.student_id, s.student_no, s.name, s.gender, " +
                        "s.phone, s.email, s.status, c.class_name " +
                        "FROM student s " +
                        "JOIN class c ON s.class_id = c.class_id " +
                        "JOIN teaching t ON t.class_id = c.class_id " +
                        "WHERE t.teacher_id = ? " +
                        "AND s.class_id = ? " + // 添加班级过滤
                        "AND (s.student_no LIKE ? OR s.name LIKE ?)";

                ResultSet rs = conn.executeSql(sql, new Object[]{
                        teacherId,
                        classId,  // 添加班级ID参数
                        "%" + keyword + "%",
                        "%" + keyword + "%"
                });

                StringBuilder json = new StringBuilder("[");
                boolean first = true;

                while (rs.next()) {
                    if (!first) {
                        json.append(",");
                    }
                    first = false;
                    json.append("{")
                            .append("\"student_id\":").append(rs.getInt("student_id")).append(",")
                            .append("\"student_no\":\"").append(escapeJson(rs.getString("student_no"))).append("\",")
                            .append("\"name\":\"").append(escapeJson(rs.getString("name"))).append("\",")
                            .append("\"gender\":\"")
                            .append(rs.getInt("gender") == 1 ? "男" : "女")
                            .append("\",")
                            .append("\"phone\":\"").append(escapeJson(rs.getString("phone"))).append("\",")
                            .append("\"email\":\"").append(escapeJson(rs.getString("email"))).append("\",")
                            .append("\"status\":").append(rs.getInt("status")).append(",") // 添加状态字段
                            .append("\"class_name\":\"").append(escapeJson(rs.getString("class_name")))
                            .append("\"}");
                }
                json.append("]");

                response.setContentType("application/json;charset=UTF-8");
                response.getWriter().print(json.toString());
            }
        } catch (Exception e) {
            e.printStackTrace();
            response.sendRedirect("teacher.jsp?section=students&error=搜索失败");
        }
    }

    private String escapeJson(String input) {
        if (input == null) return "";
        return input.replace("\\", "\\\\")
                .replace("\"", "\\\"")
                .replace("\b", "\\b")
                .replace("\f", "\\f")
                .replace("\n", "\\n")
                .replace("\r", "\\r")
                .replace("\t", "\\t");
    }
}